//
//  NvCustomStickerFilterViewController.m
//  SDKDemo
//
//  Created by dx on 2018/6/21.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvCustomStickerViewController.h"
#import "NvAssetCollectionViewCell.h"
#import "NvAssetCellModel.h"
#import "NvDragView.h"
#import "NvAssetManager.h"
#import "NvMoreCustomStickerViewController.h"
#import "UIImage+GIF.h"
#import "NvsStreamingContext.h"
#import "NvsVideoTrack.h"
#import "NvEditStickerViewController.h"
#import "NvsVideoClip.h"
#import "NvSDKUtils.h"

@interface NvCustomStickerViewController () <UICollectionViewDelegate, UICollectionViewDataSource, NvsStreamingContextDelegate>
//图片展示视图
@property (nonatomic, strong) UIImageView *photoView;
//动效视图
@property (nonatomic, strong) UIView *animationPanelView;//最外层
@property (nonatomic, strong) UICollectionView *animationCollectionView;//滤镜滑动视图
@property (nonatomic, strong) NSMutableArray *customStickerArray;//滤镜数组

@property (nonatomic, strong) UIButton *finishButton;//完成按钮
@property (nonatomic, strong) NvDragView *dragView;//拖拽框
@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NvsStreamingContext *context;
@property (nonatomic, strong) NvsVideoTrack *videoTrack;
@property (nonatomic, strong) NvsTimeline *timeline;
@property (nonatomic, strong) NvsLiveWindow *liveWindow;
@property (nonatomic, strong) NSString *tempFile;
@property (nonatomic, strong) NSString *currentTemplateUuid;
@property (nonatomic, strong) NSMutableDictionary *reservedAssetName;
@property (nonatomic, assign) int currentCellIndex;
@property (nonatomic, strong) NSString *uuid;
@property (nonatomic, strong) UIView *line;

@end

@implementation NvCustomStickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择动效";
    [self addSubViews];
    
    self.customStickerArray = [NSMutableArray array];
    
    self.assetManager = [NvAssetManager sharedInstance];
    NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sticker/custom"];
    [self.assetManager searchReservedAssets:ASSET_CUSTOM_ANIMATED_STICKER bundlePath:itemPath];
    [self.assetManager searchLocalAssets:ASSET_CUSTOM_ANIMATED_STICKER];
    
    [self initLiveWindow];
    [self createTimeline];
    [self createTempImage];
    [self initReservedAssetName];
}

- (void)initReservedAssetName {
    _reservedAssetName = NSMutableDictionary.new;
    [_reservedAssetName setObject:@"无效果" forKey:@"E14FEE65-71A0-4717-9D66-3397B6C11223"];
    [_reservedAssetName setObject:@"旋入" forKey:@"5D9FA998-7600-492F-9DF4-BC2FA5E869BD"];
}

- (void)initSeplineView {
    float navbarHeight = 64*SCREANSCALE;
    UIView *sepline = [[UIView alloc] initWithFrame:CGRectMake(0, 521*SCREANSCALE - navbarHeight, SCREANWIDTH, SCREANSCALE)];
    sepline.backgroundColor = [UIColor nv_colorWithHexRGB:@"#979797"];
    [self.view addSubview:sepline];
}

- (void)initLiveWindow {
    self.liveWindow = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, SCREANWIDTH, SCREANWIDTH)];
    [self.view addSubview:self.liveWindow];
    self.liveWindow.hidden = YES;
}

- (void)createTimeline {
    self.context = [NvsStreamingContext sharedInstance];
    NvsVideoResolution videoEditRes;
    videoEditRes.imageWidth = 720;
    videoEditRes.imageHeight = 720;
    videoEditRes.imagePAR = (NvsRational){1, 1};
    NvsRational videoFps = {25, 1};
    NvsAudioResolution audioEditRes;
    audioEditRes.sampleRate = 48000;
    audioEditRes.channelCount = 2;
    audioEditRes.sampleFormat = NvsAudSmpFmt_S16;
    self.timeline = [self.context createTimeline:&videoEditRes videoFps:&videoFps audioEditRes:&audioEditRes];
    self.videoTrack = [self.timeline appendVideoTrack];
    [self.context connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    self.context.delegate = self;
    
    NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sticker/background"];
    NSString *imageFile = [itemPath stringByAppendingPathComponent:@"custom.png"];
    [self.videoTrack addClip:imageFile inPoint:0];
    [self.videoTrack changeOutPoint:0 newOutPoint:8000000];
}

- (void)dealloc {
    NSFileManager *fileManager = NSFileManager.new;
    if ([fileManager fileExistsAtPath:self.tempFile]) {
        [fileManager removeItemAtPath:self.tempFile error:nil];
    }
}

- (void)createTempImage {
    NSString *tempPath = [NvUtils getTempPath];
    self.uuid = [NvUtils uuidString];
    self.tempFile = [tempPath stringByAppendingPathComponent:[self.uuid stringByAppendingString:@".png"]];
    [UIImagePNGRepresentation(self.image) writeToFile:self.tempFile atomically:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateCustomStickers];
    [self.animationCollectionView reloadData];
}

- (void)updateCustomStickers {
    NSArray *array = [self.assetManager getUsableAssets:ASSET_CUSTOM_ANIMATED_STICKER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([self isAssetExist:asset.uuid])
            continue;
        NvAssetCellModel *assetModel = NvAssetCellModel.new;
        assetModel.displayName = asset.isReserved ? _reservedAssetName[asset.uuid] : asset.name;
        assetModel.cover = [asset.coverUrl absoluteString];
        assetModel.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
        assetModel.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
        assetModel.package = asset.uuid;
        [self.customStickerArray insertObject:assetModel atIndex:0];
    }
}

- (BOOL)isAssetExist:(NSString *)uuid {
    for (NvAssetCellModel *item in self.customStickerArray) {
        if ([item.package isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addSubViews {
    self.animationPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, 465*SCREANSCALE, SCREEN_WDITH, 80*SCREANSCALE)];
    
    UIButton *moreB = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreB setImage:[NvUtils imageWithName:@"NvsFilterMore"] forState:UIControlStateNormal];
    moreB.frame = CGRectMake(13 * SCREANSCALE, 10*SCREANSCALE, 35 * SCREANSCALE, 25 * SCREANSCALE);
    [moreB addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moreL = [[UILabel alloc]initWithFrame:CGRectMake(15 * SCREANSCALE, 55 * SCREANSCALE, 30 * SCREANSCALE, 21 * SCREANSCALE)];
    moreL.text = @"更多";
    moreL.textColor = [UIColor nv_colorWithHexRGB:@"#979797"];
    moreL.font = [NvUtils fontWithSize:15 * SCREANSCALE];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(60*SCREANSCALE, 80*SCREANSCALE);
    layout.minimumLineSpacing = 20*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.animationCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(88 * SCREANSCALE, 0*SCREANSCALE, SCREEN_WDITH - 88 * SCREANSCALE, 80*SCREANSCALE) collectionViewLayout:layout];
    self.animationCollectionView.delegate = self;
    self.animationCollectionView.dataSource = self;
    self.animationCollectionView.backgroundColor = [UIColor clearColor];
    self.animationCollectionView.showsHorizontalScrollIndicator = NO;
    [self.animationCollectionView registerClass:[NvAssetCollectionViewCell class] forCellWithReuseIdentifier:@"NvAssetCollectionViewCell"];
    
    [self.animationPanelView addSubview:moreB];
    [self.animationPanelView addSubview:moreL];
    [self.animationPanelView addSubview:self.animationCollectionView];
    
    [self.view addSubview:self.animationPanelView];

    [self initFinishButton];
    [self initPhotoView];
}

- (void)initFinishButton {
    self.finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishButton setImage:[NvUtils imageWithName:@"Nvcheck - material"] forState:UIControlStateNormal];
    [self.finishButton addTarget:self action:@selector(finishButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.finishButton.frame = CGRectMake(175*SCREANSCALE, 568*SCREANSCALE, 25*SCREANSCALE, 20*SCREANSCALE);
    [self.view addSubview:self.finishButton];
    self.line = [UIView new];
    self.line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@1);
        make.bottom.equalTo(self.finishButton.mas_top).offset(-12*SCREANSCALE);
    }];
}

- (void)initPhotoView {
    self.photoView = [[UIImageView alloc] init];
    [self.photoView setImage:self.image];
    self.photoView.userInteractionEnabled = YES;
    [self.view addSubview:self.photoView];
    [self setPhotoViewFrame];
}

- (void)setPhotoViewFrame {
    float centerPartHeight = 455*SCREANSCALE;
    if (self.image.size.width < self.image.size.height) {
        float height = SCREANWIDTH;
        float width = self.image.size.width/self.image.size.height*height;
        float x = (SCREANWIDTH - width)/2;
        float y = (centerPartHeight - height)/2;
        self.photoView.frame = CGRectMake(x, y, width, height);
    } else if (self.image.size.width > self.image.size.height) {
        float width = SCREANWIDTH;
        float height = self.image.size.height/self.image.size.width*width;
        float x = 0;
        float y = (centerPartHeight - height)/2;
        self.photoView.frame = CGRectMake(x, y, width, height);
    } else {
        float width = SCREANWIDTH;
        float height = SCREANWIDTH;
        float x = 0;
        float y = (centerPartHeight - height)/2;
        self.photoView.frame = CGRectMake(x, y, width, height);
    }
}

#pragma mark 更多按钮点击
- (void)moreClick:(UIButton *)sender{
    NvMoreCustomStickerViewController *vc = NvMoreCustomStickerViewController.new;
    vc.type = ASSET_CUSTOM_ANIMATED_STICKER;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)finishButtonClicked:(UIButton *)sender{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:self.tempFile]) {
        NSString *dir = [NvUtils getCustomAnimatedStickerPicPath];
        NSString *destFilePath = [dir stringByAppendingPathComponent:[self.uuid stringByAppendingString:@".png"]];
        [fileManager copyItemAtPath:self.tempFile toPath:destFilePath error:nil];
        
        
        
        NvCustomStickerInfo *info = NvCustomStickerInfo.new;
        info.uuid = self.uuid;
        info.templateUuid =self.currentTemplateUuid;
        info.imagePath = destFilePath;
        info.order = (int)_assetManager.customStickerDict.count;
        
        
        if (![NvUtils isStringEmpty:self.currentTemplateUuid]) {
            [_assetManager.customStickerDict setObject:info forKey:info.uuid];
            [_assetManager setAssetInfoToUserDefaults];
        }
    }
    
    if (self.timeline) {
        [self.context removeTimeline:self.timeline];
    }
    for (id vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:NvEditStickerViewController.class]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.customStickerArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvAssetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvAssetCollectionViewCell" forIndexPath:indexPath];
    [cell renderCellWithItem:self.customStickerArray[indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.liveWindow.hidden = NO;
    self.photoView.hidden = YES;

    [self removeAllStickers];
    NvAssetCellModel *currentModel = self.customStickerArray[self.currentCellIndex];
    currentModel.selected = NO;
    
    NvAssetCellModel *cellModel = self.customStickerArray[indexPath.row];
    cellModel.selected = YES;
    self.currentCellIndex = (int)indexPath.row;
    self.currentTemplateUuid = cellModel.package;
    [self addCustomSticker:cellModel.package];
    [self playbackTimeline:0];
    
    [collectionView reloadData];
}

- (void)removeAllStickers {
    NvsTimelineAnimatedSticker *sticker = [self.timeline getFirstAnimatedSticker];
    while (sticker) {
        sticker = [self.timeline removeAnimatedSticker:sticker];
    }
}
- (void)addCustomSticker:(NSString *)packageId {
    [self.timeline addCustomAnimatedSticker:0 duration:self.timeline.duration animatedStickerPackageId:packageId customImagePath:self.tempFile];
}

- (void)playbackTimeline:(int64_t)pos {
    [self.context playbackTimeline:self.timeline startTime:pos endTime:-1 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
}

- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
//    NSLog(@"%lld", position);
}

@end
